<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加图层"
    width="600px"
    :before-close="handleClose"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <!-- 图层类型选择 -->
      <el-form-item label="图层类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择图层类型" @change="onTypeChange">
          <el-option
            v-for="type in layerTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          >
            <div style="display: flex; align-items: center;">
              <el-icon style="margin-right: 8px;">
                <component :is="type.icon" />
              </el-icon>
              <span>{{ type.label }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 图层名称 -->
      <el-form-item label="图层名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入图层名称" />
      </el-form-item>

      <!-- 3D Tiles 配置 -->
      <template v-if="form.type === '3dtiles'">
        <el-form-item label="数据URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入3D Tiles数据URL">
            <template #append>
              <el-button @click="selectFile">选择文件</el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="屏幕空间误差">
          <el-input-number v-model="form.maximumScreenSpaceError" :min="1" :max="128" />
        </el-form-item>
        
        <el-form-item label="内存限制(MB)">
          <el-input-number v-model="form.maximumMemoryUsage" :min="128" :max="2048" />
        </el-form-item>
      </template>

      <!-- TMS 配置 -->
      <template v-if="form.type === 'tms'">
        <el-form-item label="服务URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入TMS服务URL" />
        </el-form-item>
        
        <el-form-item label="最小层级">
          <el-input-number v-model="form.minimumLevel" :min="0" :max="20" />
        </el-form-item>
        
        <el-form-item label="最大层级">
          <el-input-number v-model="form.maximumLevel" :min="0" :max="20" />
        </el-form-item>
      </template>

      <!-- WMS 配置 -->
      <template v-if="form.type === 'wms'">
        <el-form-item label="服务URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入WMS服务URL" />
        </el-form-item>
        
        <el-form-item label="图层名称" prop="layers">
          <el-input v-model="form.layers" placeholder="请输入WMS图层名称" />
        </el-form-item>
        
        <el-form-item label="图像格式">
          <el-select v-model="form.format" placeholder="选择图像格式">
            <el-option label="PNG" value="image/png" />
            <el-option label="JPEG" value="image/jpeg" />
            <el-option label="GIF" value="image/gif" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="透明背景">
          <el-switch v-model="form.transparent" />
        </el-form-item>
      </template>

      <!-- GeoJSON 配置 -->
      <template v-if="form.type === 'geojson'">
        <el-form-item label="数据源">
          <el-radio-group v-model="form.dataSource">
            <el-radio label="url">URL地址</el-radio>
            <el-radio label="file">本地文件</el-radio>
            <el-radio label="text">文本输入</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="form.dataSource === 'url'" label="数据URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入GeoJSON文件URL" />
        </el-form-item>
        
        <el-form-item v-if="form.dataSource === 'file'" label="选择文件">
          <el-button @click="selectGeoJSONFile">选择GeoJSON文件</el-button>
          <span v-if="form.fileName" style="margin-left: 8px; color: #409eff;">
            {{ form.fileName }}
          </span>
        </el-form-item>
        
        <el-form-item v-if="form.dataSource === 'text'" label="GeoJSON数据">
          <el-input
            v-model="form.geoJsonText"
            type="textarea"
            :rows="6"
            placeholder="请粘贴GeoJSON数据"
          />
        </el-form-item>
        
        <el-form-item label="样式配置">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="填充颜色" label-width="80px">
                <el-color-picker v-model="form.fillColor" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="边框颜色" label-width="80px">
                <el-color-picker v-model="form.outlineColor" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="透明度" label-width="80px">
                <el-slider v-model="form.fillOpacity" :min="0" :max="1" :step="0.1" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="边框宽度" label-width="80px">
                <el-input-number v-model="form.outlineWidth" :min="1" :max="10" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </template>

      <!-- 通用设置 -->
      <el-form-item label="默认显示">
        <el-switch v-model="form.visible" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          添加图层
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Box, Map, DataLine, Location } from '@element-plus/icons-vue'
import { useLayerStore } from '../stores/layerStore'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean
})

const emit = defineEmits(['update:visible'])

const layerStore = useLayerStore()
const formRef = ref()
const loading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 图层类型定义
const layerTypes = [
  { label: '3D Tiles', value: '3dtiles', icon: 'Box' },
  { label: 'TMS瓦片', value: 'tms', icon: 'Map' },
  { label: 'WMS服务', value: 'wms', icon: 'Map' },
  { label: 'GeoJSON', value: 'geojson', icon: 'Location' }
]

// 表单数据
const form = reactive({
  type: '',
  name: '',
  url: '',
  visible: true,
  // 3D Tiles 相关
  maximumScreenSpaceError: 16,
  maximumMemoryUsage: 512,
  // TMS 相关
  minimumLevel: 0,
  maximumLevel: 18,
  // WMS 相关
  layers: '',
  format: 'image/png',
  transparent: true,
  // GeoJSON 相关
  dataSource: 'url',
  fileName: '',
  geoJsonText: '',
  geoJsonData: null,
  fillColor: '#ffff00',
  outlineColor: '#ffffff',
  fillOpacity: 0.6,
  outlineWidth: 2
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择图层类型', trigger: 'change' }],
  name: [{ required: true, message: '请输入图层名称', trigger: 'blur' }],
  url: [{ required: true, message: '请输入URL地址', trigger: 'blur' }],
  layers: [{ required: true, message: '请输入WMS图层名称', trigger: 'blur' }]
}

// 类型改变时的处理
const onTypeChange = (type) => {
  form.name = `${layerTypes.find(t => t.value === type)?.label || ''}_${Date.now()}`
}

// 选择文件
const selectFile = async () => {
  if (window.require) {
    const { ipcRenderer } = window.require('electron')
    const result = await ipcRenderer.invoke('show-open-dialog', {
      properties: ['openFile'],
      filters: [
        { name: '3D Tiles', extensions: ['json'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      form.url = result.filePaths[0]
    }
  }
}

// 选择GeoJSON文件
const selectGeoJSONFile = async () => {
  if (window.require) {
    const { ipcRenderer } = window.require('electron')
    const result = await ipcRenderer.invoke('show-open-dialog', {
      properties: ['openFile'],
      filters: [
        { name: 'GeoJSON', extensions: ['geojson', 'json'] },
        { name: '所有文件', extensions: ['*'] }
      ]
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      const filePath = result.filePaths[0]
      form.fileName = filePath.split('/').pop()
      
      // 读取文件内容
      const fileResult = await ipcRenderer.invoke('read-file', filePath)
      if (fileResult.success) {
        try {
          form.geoJsonData = JSON.parse(fileResult.data)
        } catch (error) {
          ElMessage.error('GeoJSON文件格式错误')
        }
      }
    }
  }
}

// 提交表单
// 在 AddLayerDialog.vue 的 handleSubmit 方法中，修改如下：

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    const layerConfig = {
      name: form.name,
      type: form.type,
      visible: form.visible
    }
    
    // 根据图层类型添加特定配置
    switch (form.type) {
      case '3dtiles':
        layerConfig.url = form.url
        layerConfig.maximumScreenSpaceError = form.maximumScreenSpaceError
        layerConfig.maximumMemoryUsage = form.maximumMemoryUsage
        break
        
      case 'tms':
        layerConfig.url = form.url
        layerConfig.minimumLevel = form.minimumLevel
        layerConfig.maximumLevel = form.maximumLevel
        break
        
      case 'wms':
        layerConfig.url = form.url
        layerConfig.layers = form.layers
        layerConfig.format = form.format
        layerConfig.transparent = form.transparent
        layerConfig.parameters = {
          format: form.format,
          transparent: form.transparent
        }
        break
        
      case 'geojson':
        layerConfig.dataSource = form.dataSource
        
        if (form.dataSource === 'url') {
          layerConfig.url = form.url
        } else if (form.dataSource === 'file') {
          if (!form.geoJsonData) {
            throw new Error('请选择GeoJSON文件')
          }
          layerConfig.data = form.geoJsonData
        } else if (form.dataSource === 'text') {
          if (!form.geoJsonText.trim()) {
            throw new Error('请输入GeoJSON数据')
          }
          try {
            layerConfig.data = JSON.parse(form.geoJsonText)
          } catch (error) {
            throw new Error('GeoJSON格式错误')
          }
        }
        
        // 样式配置
        layerConfig.fillColor = form.fillColor
        layerConfig.outlineColor = form.outlineColor
        layerConfig.fillOpacity = form.fillOpacity
        layerConfig.outlineWidth = form.outlineWidth
        break
    }
    
    console.log('准备添加图层，配置:', layerConfig)
    
    // 添加图层
    await layerStore.addLayer(layerConfig)
    
    console.log('图层添加成功')
    ElMessage.success('图层添加成功')
    handleClose()
    
  } catch (error) {
    console.error('添加图层失败:', error)
    ElMessage.error(error.message || '添加图层失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    type: '',
    name: '',
    url: '',
    visible: true,
    maximumScreenSpaceError: 16,
    maximumMemoryUsage: 512,
    minimumLevel: 0,
    maximumLevel: 18,
    layers: '',
    format: 'image/png',
    transparent: true,
    dataSource: 'url',
    fileName: '',
    geoJsonText: '',
    geoJsonData: null,
    fillColor: '#ffff00',
    outlineColor: '#ffffff',
    fillOpacity: 0.6,
    outlineWidth: 2
  })
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-color-picker) {
  width: 100%;
}

:deep(.el-slider) {
  margin: 8px 12px;
}
</style>